import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
import ctypes
from tkinter import ttk
import numpy as np


 
def wavelength_to_rgb(wavelength, gamma=0.8):
    wavelength = float(wavelength)
    if wavelength >= 380 and wavelength <= 440:
        attenuation = 0.3 + 0.7 * (wavelength - 380) / (440 - 380)
        R = ((-(wavelength - 440) / (440 - 380)) * attenuation) ** gamma
        G = 0.0
        B = (1.0 * attenuation) ** gamma
    elif wavelength >= 440 and wavelength <= 490:
        R = 0.0
        G = ((wavelength - 440) / (490 - 440)) ** gamma
        B = 1.0
    elif wavelength >= 490 and wavelength <= 510:
        R = 0.0
        G = 1.0
        B = (-(wavelength - 510) / (510 - 490)) ** gamma
    elif wavelength >= 510 and wavelength <= 580:
        R = ((wavelength - 510) / (580 - 510)) ** gamma
        G = 1.0
        B = 0.0
    elif wavelength >= 580 and wavelength <= 645:
        R = 1.0
        G = (-(wavelength - 645) / (645 - 580)) ** gamma
        B = 0.0
    elif wavelength >= 645 and wavelength <= 750:
        attenuation = 0.3 + 0.7 * (750 - wavelength) / (750 - 645)
        R = (1.0 * attenuation) ** gamma
        G = 0.0
        B = 0.0
    else:
        R = 0.0
        G = 0.0
        B = 0.0
    R *= 255
    G *= 255
    B *= 255
    return (int(R), int(G), int(B))



def rgb_wave(img):
    r_channel, g_channel, b_channel = img.split()
    
    r = np.mean(np.array(r_channel))
    g = np.mean(np.array(g_channel))
    b = np.mean(np.array(b_channel))
    
    
    error = []
    wave  = []
    for x in range(0,381,1):
        error.append(abs(wavelength_to_rgb(380+x)[0] - r) + abs(wavelength_to_rgb(380+x)[1] - g) + abs(wavelength_to_rgb(380+x)[2] - b))
        wave.append(380 + x)

    return wave[error.index(min(error))]
    
             



# 创建主窗口
root = tk.Tk()
root.configure(bg='lightgray')


# 界面优化代码---------------------------------
# 调用api设置成由应用程序缩放
ctypes.windll.shcore.SetProcessDpiAwareness(1)
# 调用api获得当前的缩放因子
ScaleFactor=ctypes.windll.shcore.GetScaleFactorForDevice(0)
# 设置缩放因子
root.tk.call('tk', 'scaling', ScaleFactor/75)
#--------------------------------------------


root.title("RGB to Wavelength Calculator")
root.geometry('900x900')     # 设置窗口大小
root.config(bg="#FFF5EE")






# 定义处理图像的函数
def process_image(image_path):
    img = Image.open(image_path).convert("RGB")
    result_label.config(text=f"预测的波长为: {rgb_wave(img)} nm",font=('KaiTi',20))

# 定义上传图片的回调函数
def upload_image():
    file_path = filedialog.askopenfilename()
    if file_path:
        # 显示选择的图片
        img = Image.open(file_path)
        img.thumbnail((300, 300))  # 调整显示尺寸
        img = ImageTk.PhotoImage(img)
        image_label.config(image=img)
        image_label.image = img

        # 处理图像并显示结果
        process_image(file_path)

# 创建上传图片按钮
image = Image.open("upload_image_logo.png").resize((50, 50))
logo = ImageTk.PhotoImage(image)
upload_button = tk.Button(root, text="上传你的图片", font = ('楷体',20),
                          relief = 'raised',activebackground = 'gray',
                          command=upload_image,image=logo,compound='left')
upload_button.pack(pady=10)
upload_button.config(image=logo)


# 显示图片标签 
image_label = tk.Label(root)
image_label.pack(pady=10)

# 显示识别结果的标签
result_label = tk.Label(root, text="预测的波长为：",font= ('KaiTi',20))
result_label.pack(pady=100)

# 退出按钮
exit_button = tk.Button(root,text='退出',font=('KaiTi',20),
                        relief='raised',command=root.quit)
exit_button.pack(pady=150)

# 运行主循环
root.mainloop()
